/**
 * @Copyright 
 * @Project inetdisk
 * @CreateTime 2015-11-4 上午10:00:14
 */
package ren.wxyz.inetdisk.dao.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import ren.wxyz.inetdisk.dao.FileStorageDao;

/**
 * <p>
 * 本地文件存储访问
 * </p>
 * @Author wxyz
 * @CreateTime 2015-11-4 上午10:00:14 init class
 */
//@Repository
public class FileLocalStorageDaoImpl implements FileStorageDao {

	/**
	 * 默认缓存大小
	 */
	private static final int BUFFER_SIZE = 1024 * 8;
	
	/**
	 * 当前缓存大小
	 */
	private final int buffSize;
	
	/**
	 * 本地的存储根目录
	 */
	private final String rootDir;
	
	/**
	 * <p>
	 * 初始化本地文件访问，设置本地的根目录
	 * </p>
	 * @param rootDir 根目录
	 * @CreateTime 2015-11-4 上午11:02:58 create constructor
	 */
	public FileLocalStorageDaoImpl(String rootDir) {
		this.buffSize = BUFFER_SIZE;
		this.rootDir = rootDir;
	}
	
	/**
	 * <p>
	 * 初始化本地文件访问，设置处理缓存和本地的根目录
	 * </p>
	 * @param buffSize 处理缓存大小
	 * @param rootPath 根目录
	 * @CreateTime 2015-11-4 上午11:03:39 create constructor
	 */
	public FileLocalStorageDaoImpl(int buffSize, String rootDir) {
		this.buffSize = buffSize;
		this.rootDir = rootDir;
	}
	
	@Override
	public boolean readTo(OutputStream out, String path) throws IOException {
		
		FileInputStream fin = null;
		
		try {
			fin = new FileInputStream(new File(rootDir, path));
			
			byte[] buff = new byte[buffSize];
			int len = 0;
			while ((len = fin.read(buff)) > 0) {
				out.write(buff, 0, len);
			}
			out.flush();
			
			return true;
		}
		// 文件不存在时，返回false
		catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		}
		catch (IOException e) {
			throw e;
		}
		finally {
			if (null != fin) {
				fin.close();
			}
		}
	}

	@Override
	public boolean writeFrom(InputStream in, String path) throws IOException {
		FileOutputStream fos = null;
		
		try {
			File f = new File(rootDir, path);
			if (!f.getParentFile().exists()) {
				f.mkdirs();
			}
			fos = new FileOutputStream(f);
			
			byte[] buff = new byte[buffSize];
			int len = 0;
			while ((len = in.read(buff)) > 0) {
				fos.write(buff, 0, len);
			}
			fos.flush();
			
			return true;
		}
		// 文件不存在时，返回false
		catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		}
		catch (IOException e) {
			throw e;
		}
		finally {
			if (null != fos) {
				fos.close();
			}
		}
	}

}
